<template>
  <div class="log flex flex-1 h-0"
       v-loading="loading">
    <div class="log__left flex-1 flex flex-col w-0">
      <el-alert type="warning"
                v-if="isOff"
                class="log__left--alert">
        <template v-slot:title>
          <i class="cuifont icon_error_circle"></i>
          {{$t('custom.component.cardApp.integrationText')}}
        </template>
      </el-alert>
      <el-header class="log--panel flex justify-between"
                 style="padding-top:0">
        <LogPanelItem :total="this.data.sync.subjectCode === 'DROPBOX' && this.data.auth === 'user'? 0 : totalApi.length"
                      :name="$t('custom.apiCount')" />
        <LogPanelItem :total="totalSuccessApi.length"
                      :name="$t('custom.successCount')"
                      type="success" />
        <LogPanelItem :total="totalFailApi"
                      :name="$t('custom.failCount')"
                      type="error" />
      </el-header>

      <LogList :data="data"
               ref="log-list"
               :loading.sync="loading"
               :historyLoading="historyLoading" />
    </div>
    <div class="log__right flex-1 flex flex-col w-0"
         v-loading="historyLoading||historyLogLoading">
      <el-form inline
               v-if="logDetail"
               class="log__right-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item class="flex flex-col"
                          :label="$t('custom.syncFrequency')">
              {{logDetail.syncRate==="null" || logDetail.syncRate===null? logDetail.syncRate :`${logDetail.syncRate}  Seconds`}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="flex flex-col"
                          :label="$t('custom.acquisition')">
              {{logDetail.lastSyncDate | transformTimeZone}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="flex flex-col"
                          :label="$t('custom.ods')">
              <span :style="{'cursor':logDetail.odsUrl?'pointer':''}" @click="goToUrl(logDetail.odsUrl)">{{logDetail.name}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="flex flex-col">
              <div v-if="logDetail.apiDoc" :style="{'cursor':'pointer'}" @click="openUrl(logDetail.apiDoc)">{{$t('custom.apiUrl')}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-header class="log--panel flex justify-between"
                 style="padding-top:0">
        <LogPanelItem :total="allCount.total"
                      :name="$t('custom.syncTotal')" />
        <LogPanelItem :total="allCount.successcount"
                      :name="$t('custom.successCount')"
                      type="success" />
        <LogPanelItem :total="(allCount.total - allCount.successcount) || 0"
                      :name="$t('custom.failCount')"
                      type="error" />
      </el-header>

      <LogHistory :data="data"
                  ref="log-history"
                  :loading.sync="historyLogLoading" />
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import LogList from './log-list.vue'
import LogHistory from './log-history.vue'
import LogPanelItem from './log-panel-item.vue'
import {transformTimeZone} from "@/filters";
export default {
  name: 'Log',
  components: {
    LogList,
    LogPanelItem,
    LogHistory
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    isOff: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      logs: [],
      allCount: {},
      loading: false,
      historyLoading: false,
      historyLogLoading: false,
      selectedLog: {},
      logDetail: null
    }
  },

  created () {
    this.$root.eventBus.$on('event:log-list', (logs) => {
      this.logs = logs
    })
    this.$root.eventBus.$on('event:row-click', (row) => {
      this.selectedLog = row
      this.getLogDetail()
    })
    this.$root.eventBus.$on('event:all-count', (allCount) => {
      this.allCount = allCount
    })
  },
  beforeDestroy () {
    this.$root.eventBus.$off('event:log-list')
    this.$root.eventBus.$off('event:row-click')
    this.$root.eventBus.$off('event:all-count')
  },
  computed: {
    totalApi () {
      return this.logs
    },
    totalSuccessApi () {
      return this.logs.filter(i => i.status === '200 OK')
    },
    totalFailApi () {
      return this.logs.length - this.totalSuccessApi.length - this.totalPeddingApi.length
    },
    totalPeddingApi () {
      return this.logs.filter(i => !i.status && !i.lastSyncDate)
    }
  },
  watch: {
    isOff () {
      this.$refs['log-list'].getAutoHeight()
    }
  },
  methods: {
    goToUrl (url) {
      this.$emit('closeVisible')
      this.$router.push(url)
    },
    openUrl (url) {
      if (!url) return
      window.open(url, '_blank')
    },
    async getLogDetail () {
      let CancelToken = axios.CancelToken
      const { get } = this._
      const { getInfoApi } = this.$interface.apiManager
      try {
        this.historyLoading = true
        const params = {
          subjectCode: get(this.data, 'sync.subjectCode'),
          action: get(this.selectedLog, 'action', null)
        }

        let { data: response } = await getInfoApi(params, {
          cancelToken: new CancelToken(function executor (c) {
            window.getInfoApi = c
          })
        })
        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.logDetail = get(response, 'data', null)
        this.historyLoading = false
      } catch (error) {
        if (!axios.isCancel(error)) {
          this.historyLoading = false
        }
        // this.$message.error(error)
      } finally {
        // if (!axios.isCancel()) {
        //   this.historyLoading = false
        // }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.log {
  position: relative;
  overflow: hidden;
  border-top: 1px solid #f0f0f0;

  &__left {
    padding: 24px 15px 0;
    margin-bottom: 15px;
    &--alert {
      flex-shrink: 0;
      margin-bottom: 15px;
      color: #404040;
      .cuifont {
        font-size: 13px;
      }
    }
  }
  &--panel {
    padding: 15px 0;
    height: auto !important;
  }

  &__right {
    padding: 24px 15px 0;
    border-left: 1px solid #f0f0f0;
    &-form {
      .el-form-item {
        display: flex !important;
      }
      margin-bottom: 15px;
      ::v-deep .el-form-item__label {
        color: #808080;
        text-align: left;
      }
      ::v-deep .el-form-item__content {
        color: #0050b3;
        text-decoration: underline;
      }
    }
  }
}
</style>
